/* mz_math.h
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Definitions for mathematical functions not included in the standard libraries.
*/

#include "mz_math.h"

#include <algorithm>

using std::swap;



// gcd:
// Find the greatest common divisor of two numbers.
long long gcd(long long i, long long j)
{
	// If one number is zero, return the other.
	if(!i | !j)
		return i | j;
	
	// Maintain: i >= j.
	if(i < j)
		swap(i, j);
	
	// Factor out common powers of two first.
	int shift = 0;
	for( ; !((i | j) & 1); ++shift)
	{
		i >>= 1;
		j >>= 1;
	}

	while(j)
	{
		if(!(j & 1))
			j >>= 1;
		else
		{
			// If both are odd, set i to the difference (which is even).
			if(i & 1)
				i -= j;
			i >>= 1;
			
			// Either of the above operations could mess up the ordering.
			if(i < j)
				swap(i, j);
		}
	}
	
	return i << shift;
}



// choose:
// Calculate the number of combinations of k items out of n.
long long choose(long long n, long long k)
{
	if((k > n) | (k < 0) | (n < 0))
		return 0;
	if(k > (n / 2))
		k = n - k;
	
	// Each intermediate product here is equal to n Choose something,
	// so each intermediate product is integral. That means that there is
	// no reason not to do the division after each step. This is slower
	// (more divisions performed) but can handle much larger numbers.
	long long result = 1;
	for(int i = 0; i < k; ++i)
	{
		result *= n - i;
		result /= i + 1;
	}
	
	return result;
}



// permute:
// Calculate the numer of permutations that can be formed by choosing
// k items out of n.
long long permute(long long n, long long k)
{
	if((k > n) | (k < 0) | (n < 0))
		return 0;
	
	// The product of the numbers from (n - k) to n.
	long long result = 1;
	for(int i = 0; i < k; ++i)
		result *= n - i;
	
	return result;
}



/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */

